<?php


namespace app\api\controller\v1;


use app\exception\CategoryException;
use app\exception\ProductException;
use app\validate\api\Count;
use app\validate\api\IDMustBePositiveInt;
use think\annotation\Route;
use think\Exception;
use app\api\model\Product as ProductModel;
use think\Model;


class Product
{

    /**
     * @Route("v1/product/recent",method="GET",https=0)
     * @param int $count
     *
     * @return mixed
     * @throws Exception
     */
    public function getRecent($count=15)
    {

        (new Count())->goCheck();
        $result = ProductModel::getMostRecent($count);
        if($result->isEmpty()){
            throw new ProductException();
        }
        return json($result);
    }

    /**
     * @Route("v1/product/by_category/:id",method="GET",https=0)
     * @throws Exception
     */
    public function getProductsByCategoryID($id): \think\Collection
    {
        (new IDMustBePositiveInt())->goCheck();
        $result = ProductModel::getProductByCategoryID($id);
        if($result->isEmpty()){
            throw new CategoryException();
        }
        return $result;
    }
    /**
     * @param $id
     * @Route ("v1/product/:id",method="GET",https=0)
     *
     * @return mixed
     * @throws Exception
     */
    public function getOne($id){
        (new IDMustBePositiveInt())->goCheck();
        $result = ProductModel::getProductDetail($id);
        if($result->isEmpty()){
            throw new ProductException();
        }
        return json($result);
    }

}